import axios from 'axios'
import type { AxiosInstance, AxiosResponse } from 'axios'
import { useAuth } from '@/composables/auth'

const baseURL = 'http://localhost:8000'

const api: AxiosInstance = axios.create({
  baseURL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => response,
  async (error) => {
    const originalRequest = error.config
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      const { refreshAccessToken } = useAuth()
      const refreshed = await refreshAccessToken()
      
      if (refreshed) {
        const token = localStorage.getItem('token')
        originalRequest.headers.Authorization = `Bearer ${token}`
        return api(originalRequest)
      }
    }
    return Promise.reject(error)
  }
)

export default api 